873B - Balanced Substring - CodeForces Solution


dp implementation *1500

Please click on ads to support us..

Python Code:

from itertools import accumulate
n,s = int(input()),[*accumulate(map(lambda x: 2*int(x)-1,input()))]
l = {0:-1}; c = 0
for x,y in enumerate(s):
    l[y]=e=l.get(y,x)
    c = max(c,x-e)
print(c)

C++ Code:

//بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
template<typename T> using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define Samo7a ios_base::sync_with_stdio(false);cin.tie(nullptr); cout.tie(nullptr);
#define re return
#define FX(n) fixed << setprecision(n)
#define endl '\n'
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define pb push_back
#define eb emplace_back
#define pi acos(-1)
#define F first
#define S second
const int N = 2e3 + 10, MOD = 1e9 + 7;
const int dx[]{1, -1, 0, 0, 1, -1, 1, -1};
const int dy[]{0, 0, 1, -1, 1, -1, -1, 1};

inline void debugMode() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}

//الشَّيْطَانُ يَعِدُكُمُ الْفَقْرَ وَيَأْمُرُكُم بِالْفَحْشَاءِ ۖ وَاللَّهُ يَعِدُكُم مَّغْفِرَةً مِّنْهُ وَفَضْلًا ۗ وَاللَّهُ وَاسِعٌ عَلِيمٌ (268)
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//
/*
 id:
 idea:
 */




void TestCase() {
    int n;
    string s;
    cin >> n >> s;
    map < int , int > mp;
    mp[0] = 0;
    int delta = 0;
    int mx = 0;
    for ( int i = 0 ; i < n ; i++)
    {
        (s[i] == '1')?delta++: delta--;
        if (not mp.count(delta))
            mp[delta] = i + 1;
        else
            mx = max(mx , (i + 1) - mp[delta]);
    }
    cout << mx << endl;
}

int main() {
    Samo7a
    debugMode();
    int t = 1;
    //cin >> t;
    while (t--) {
        TestCase();
    }
    re 0;
}


Comments

Submit
0 Comments
More Questions

1091A - New Year and the Christmas Ornament
1352B - Same Parity Summands
1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves
1670B - Dorms War
1716B - Permutation Chain
987A - Infinity Gauntlet
1676G - White-Black Balanced Subtrees
1716D - Chip Move
1352F - Binary String Reconstruction
1487B - Cat Cycle
1679C - Rooks Defenders
56A - Bar
1694B - Paranoid String
35A - Shell Game
1684A - Digit Minimization
43B - Letter
1017A - The Rank
1698B - Rising Sand
235A - LCM Challenge
1075B - Taxi drivers and Lyft